package com.base.cn.platform.os.config;

import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.material.CouMaterial;
import com.base.cn.platform.os.entity.course.open.CourseOpen;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.material.CouMaterialBiz;
import com.base.cn.platform.os.service.course.open.CourseOpenBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 3T获取直播回放
 */
@Component
@Slf4j
public class TTLivePlayBackScheduledTask {

    @Autowired
    private TTServiceUtils ttServiceUtils;
    @Autowired
    private CouMaterialBiz couMaterialBiz;
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CourseOpenBiz courseOpenBiz;

    /**
     * 每5分钟扫描到期直播
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void livePlayBack() {
        log.info("----------------------获取3T直播回放码，每5分钟执行一次");
        live(); //直播
        openLive(); //免费直播
    }

    private void live() {
        List<CouMaterial> couMaterialList = couMaterialBiz.find("typeKey = 'LIVE' and playType = 'TT' and playUrl = '' AND liveEndTime < now()", null, null);
        couMaterialList.stream().forEach(c -> {
            String livePlayBack = ttServiceUtils.getLivePlayBack(c.getRoomId());
            if (StringUtils.isNotEmpty(livePlayBack)) {
                c.setPlayUrl(livePlayBack);
                couMaterialBiz.updateById(c, null);
                List<CourseCatalog> courseCatalogList = courseCatalogBiz.find("materialId = " + c.getId(), null, null);
                courseCatalogList.stream().forEach(ccl -> {
                    if (ObjectUtils.isNotEmpty(ccl) && StringUtils.isEmpty(ccl.getBackCode())) {
                        ccl.setBackCode(livePlayBack);
                        courseCatalogBiz.updateById(ccl, null);
                    }
                });
            }
        });
    }
    private void openLive() {
        List<CourseOpen> courseOpenList = courseOpenBiz.find("status = 1 and playType = 'TT' and backCode is null  AND endTime < now()", null, null);
        courseOpenList.stream().forEach(c -> {
            String livePlayBack = ttServiceUtils.getLivePlayBack(c.getRoomId());
            if (StringUtils.isNotEmpty(livePlayBack)) {
                c.setBackCode(livePlayBack);
                c.setPlayBackType("VIDEO");
                courseOpenBiz.updateById(c,null);
            }
        });
    }
}
